package util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 验证码生成工具类
 *
 * @author ml
 * @create 2018-02-09--16:17
 */
public class GraphicHelper {


    /**
     * @param width        图片的宽度
     * @param height       图片的高度
     * @param imgType      图片的类型
     * @param outputStream 输出流
     * @return 返回所生成的验证码
     */
    public static String create(int width, int height, String imgType, OutputStream outputStream) {

        StringBuffer sb = new StringBuffer();

        Random random = new Random();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics graphics = image.getGraphics();

        graphics.setColor(Color.getColor("F8F8F8"));
        graphics.fillRect(0, 0, width, height);

        Color[] colors = new Color[]{Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,Color.CYAN};

//        在画板上生成打扰线条
        int xsize=50;
        for(int i=0;i<xsize;i++){
            graphics.setColor(colors[random.nextInt(colors.length)]);
            final int x =random.nextInt(width);
            final int y=random.nextInt(height);
            final int w=random.nextInt(20);
            final int h=random.nextInt(20);
            final int signA=random.nextBoolean()?1:-1;
            final int signB=random.nextBoolean()?1:-1;

            graphics.drawLine(x,y,x+w*signA,y+h*signB);


        }

//        绘制字符
        graphics.setFont(new Font("Comic Sans MS",Font.BOLD,30));
        int fsize=6;

        for (int i=0;i<fsize;i++){
            final int temp=random.nextInt(26)+97;
            String s =String.valueOf((char) temp);
            sb.append(s);
            graphics.setColor(colors[random.nextInt(colors.length)]);
//            Graphics.drawString(String str,int x,int y)-(x,y)坐标指的是左下角坐标
            graphics.drawString(s,i*(width/6),height-(height/3));

        }

        graphics.dispose();
        try {
            ImageIO.write(image,imgType,outputStream);
        }catch (IOException e){
            e.printStackTrace();
        }




        return sb.toString();
    }
}
